﻿using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Nemerle.Imperative;
using System.Windows.Forms;


namespace FTClient
{

public static class GetSocket
{
    public static ConnectSocket(server:string, port:int):Socket
    {
        mutable s:Socket = null;
        mutable hostEntry:IPHostEntry = null;
        
        
        try
        {
            // Get host related information.
            hostEntry = Dns.GetHostEntry(server);

//            mutable address=IPAddress.Parse("127.0.0.1");
            foreach(address:IPAddress in hostEntry.AddressList)
            {
                mutable ipe = IPEndPoint(address, port);
                mutable tempSocket = 
                    Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    
                _ = tempSocket.Connect(ipe);
                s = tempSocket;
                if(tempSocket.Connected)
                {
                    s = tempSocket;
                    break;
                }
                else
                {
                    continue;
                }

            }
        }
         catch
        {
           | e => _ = MessageBox.Show($"Some Exception: $(e.Message)");

        }
        s;
    }

    // This method requests the home page content for the specified server.
    public static SocketSendReceive(inFilePath:string, hash:int):void
    {
        mutable bytesSent:array[Byte]  = array(3);
        
        bytesSent[0]=(hash % 255):>Byte;
        bytesSent[1]=((hash/255) % 255):>Byte;
        bytesSent[2]=((hash/65025)%255):>Byte;
        def bytesReceived:array[Byte] = array(256);
       
        mutable s:Socket=null;
        // Create a socket connection with the specified server and port.
        mutable connection = GlobalServer.GetFileLocation(hash);
        when (connection==null)
        {
                MessageBox.Show("File not found");
                return;
        }
        s = ConnectSocket(connection.server, connection.port);
        while (s==null)
        {
            
            //connection = GlobalServer.ReDownload(hash);
            connection = GlobalServer.GetFileLocation(hash);
            when (connection==null)
            {
                MessageBox.Show("File not found");
                return;
            }
            s = ConnectSocket(connection.server, connection.port);
        }

        // Высылаем uid
        _ = s.Send(Encoding.ASCII.GetBytes(GlobalServer.uid));
        _ = s.Receive(bytesReceived);//Это для синхронизации
        // Send request to the server.
        _ = s.Send(bytesSent, bytesSent.Length, 0);  
        
        // Receive the server home page content.
        mutable bytes = 0;

        when (File.Exists(inFilePath)) 
        {
            File.Delete(inFilePath);
        }
        
       
        def fs= FileStream(inFilePath, FileMode.Append, FileAccess.Write, FileShare.Write);
        fs.Close();

        using (fs2 = File.OpenWrite(inFilePath)) 
        {

            do {
               _ = s.Receive(bytesReceived);
               bytes=bytesReceived[0];
               def writebuf:array[byte] = array(bytes);
               for (mutable i=1;i<=bytes;i++)
                   writebuf[i-1]=bytesReceived[i];
               _ = fs2.Write(writebuf,0, writebuf.Length);
            }
            while (bytes == 255);
            _ = fs2.Close();
        
        }

    }
}



}
